// 重点：动态生成拼图小区域的方法

window.onload = function () {
    var sel = getItemByID("sel"),
        playBtn = getItemByID("play"),
        imgs = getItemByID("imgs"),
        count = getItemByID("count"),
        countNum = 0,
        suc = getItemByID("suc"),
        cancel = getItemByID("cancel"),
        data,
        path;

    function getItemByID(item) {
        return document.getElementById(item);
    }

    // 拼图是否成功
    function ifSuc(current, length) {
        let goal = Array.from(Array(length + 1).keys());
        goal.shift();
        return (current.toString() === goal.toString());
    }

    // 加载数据
    function loader(level) {
        imgs.innerHTML = (data + "").replace(/(\d+)\D*/g,
            `<div class='item'><img src='./img/${level}/${path}/$1.gif' index="$1"></div>`);
        imgs.children[data.indexOf(Math.pow(level, 2))].innerHTML = "";
        count.innerHTML = countNum;
        /*
         * 总体思路：把data转换为字符串，再把每一个数字及其后面的“，”转换为一个div
         *          再把最后一个元素内容变为空。
         *
         * 正则使用g模式，表示匹配所有符合条件的
         * ()标记一个子表达式的开始和结束，(\d+）表示匹配1个或1个以上连续的数字组合，如2、45...
         * \D*表示匹配0次或多次非数字字符，在此处为匹配"，"
         * $1表示第一个子串中的内容（在此为生成的随机数），$2表示第二个...
        */
    }

    // 生成max个1~max之间的随机数
    function randomData(n) {
        let max = Math.pow(n, 2) - 1,
            randomList = [];
        while(randomList.length < max) {
            let tmp = Math.floor(Math.random() * max + 1);
            if (randomList.indexOf(tmp) === -1) {
                randomList.push(tmp);
            }
        }
        randomList.push(max + 1);
        return randomList;
        // return [1,2,3,4,5,6,7,9,8]
    }

    // 初始化图片区域
    function initImgs(level) {
        countNum = 0;
        imgs.style.display = "flex";
        imgs.style.width = 80 * level + "px";
        imgs.style.height = 80 * level + "px";
    }

    // 交换图片
    function change(blankPos, replacePos, level) {
        let length = Math.pow(level, 2);
        data[blankPos] = data[replacePos];
        data[replacePos] = length;
        countNum += 1;
        loader(level);
    }

    // 点击开始游戏
    playBtn.onclick = function () {
        path = Math.floor(Math.random()*3) + 1;
        var that = this;
        that.innerHTML = "重玩";
        var level = parseInt(sel.value);
        data = randomData(level);
        initImgs(level);
        loader(level);
        document.onkeyup = function (e) {
            let event = e || window.event,
                code = event.keyCode,
                length = Math.pow(level, 2),
                blankPos = data.indexOf(length),// 空白div的位值索引
                replacePos;
            switch(true){
                case code === 37:  // left
                    replacePos = blankPos + 1;
                    if ((replacePos % level) != 0){
                        change(blankPos, replacePos, level);
                    }
                    break;
                case code === 38:   // up
                    replacePos = blankPos + level;
                    if (replacePos < length){
                        change(blankPos, replacePos, level);
                    }
                    break;
                case code === 39:   // right
                    replacePos = blankPos - 1;
                    if (((replacePos+1) % level) != 0){
                        change(blankPos, replacePos, level);
                    }
                    break;
                case code === 40:   // bottom
                    replacePos = blankPos - level;
                    if (replacePos >= 0){
                        change(blankPos, replacePos, level);
                    }
                    break;
            }
            // 拼图成功
            if (ifSuc(data, length)) {
                suc.style.display = "block";
                cancel.onclick = function () {
                    suc.style.display = "none";
                }
            }
        };

        imgs.onclick = function (e) {
            let event = e || window.event,
                target = event.srcElement || event.target,
                clickPos = data.indexOf(parseInt(target.getAttribute("index"))),
                length = Math.pow(level, 2),
                blankPos = data.indexOf(length);// 空白div的位值索引

            if (clickPos > -1) {
                if ((clickPos+1 === blankPos) && (((clickPos+1)%level)!=0) || (clickPos-1 === blankPos)&&((clickPos%level)!=0)||
                    clickPos+level==blankPos || clickPos-level==blankPos) {
                    change(blankPos, clickPos, level);
                }
            }
            console.log(data)
            // 拼图成功
            if (ifSuc(data, length)) {
                suc.style.display = "block";
                cancel.onclick = function () {
                    suc.style.display = "none";
                }
            }
        }
    };


};